// middleware/paginationService.js


class PaginationService {
    constructor(db, model) {
        this.db = db;
        this.model = model;
    }




    async paginate(page = 1, limit = 10, queryParams = {}, sort = null, fields = '*') {
        const offset = (page - 1) * limit;

        let queryConditions = [];
        let queryValues = [];

        // 构建查询条件
        for (const key in queryParams) {
            if (key.includes('searchField')) {
                queryConditions.push(`${key.replace("searchField", "")} LIKE ?`);
                queryValues.push(`%${queryParams[key]}%`);
            } else {
                queryConditions.push(`${key} = ?`);
                queryValues.push(queryParams[key]);
            }
        }

        let query = `SELECT ${fields} FROM ${this.model}`;
        if (queryConditions.length) {
            query += ' WHERE ' + queryConditions.join(' AND ');
        }

        // 添加排序功能
        if (sort) {
            query += ` ORDER BY ${sort}`;
        }

        query += ' LIMIT ? OFFSET ?';
        queryValues.push(limit, offset);

        return new Promise((resolve, reject) => {
            // 先查询数据
            this.db.query(query, queryValues, (error, results) => {
                if (error) {
                    return reject(error);
                }

                // 查询总数
                const countQuery = `SELECT COUNT(*) AS count FROM ${this.model}` +
                    (queryConditions.length ? ' WHERE ' + queryConditions.join(' AND ') : '');

                this.db.query(countQuery, queryValues.slice(0, -2), (error, countResult) => {
                    if (error) {
                        return reject(error);
                    }

                    const totalCount = countResult[0].count;
                    const totalPages = Math.ceil(totalCount / limit);

                    // 校验当前请求的页码
                    if (page > totalPages && totalPages > 0) {
                        // 如果请求的页码超出范围，返回最后一页数据
                        const newOffset = (totalPages - 1) * limit; // 新的偏移量
                        // 重新查询
                        this.db.query(query.slice(0, query.indexOf('LIMIT')) + ' LIMIT ? OFFSET ?', [...queryValues.slice(0, -2), limit, newOffset], (error, newResults) => {
                            if (error) {
                                return reject(error);
                            }
                            resolve({
                                page: totalPages,
                                limit,
                                totalCount,
                                totalPages,
                                results: newResults,
                            });
                        });
                    } else {
                        resolve({
                            page,
                            limit,
                            totalCount,
                            totalPages,
                            results,
                        });
                    }
                });
            });
        });
    }
}

















module.exports = PaginationService;